<template>
    <div class="channel" v-if="data.length > 0">
        <div class="item" v-for="item in showChannels" :key="item.id" :class="{active: item.id === id}"
             @click="selectItem(item.id)">
            <el-button type="default" plain>{{item.name}}</el-button>
        </div>
        <a href="" @click.prevent="isCollapsed = !isCollapsed">{{isCollapsed ? '展开' : '收起'}}</a>
    </div>
</template>

<script>
    // import {getChannelList} from '@/services/newsServices'
    import {mapState} from 'vuex'

    export default {
        name: "Channel",
        components: {},
        data() {
            return {
                // channels: [],
                isCollapsed: true,
                id: null // 当前选中得频道ID
            }
        },
        // 数据初始化
        async created() {
            // 获取数据
            // let resp = await getChannelList();
            // this.channels = resp;
            // 此时频道才有值
            // this.channelId = this.channels[0].channelId;
            // this.selectItem(this.data[0].id);
        },
        methods: {
            // item被点击，触发一个事件，让组件在不同的场景中实现不同的功能
            selectItem(id) {
                this.id = id;
                this.$emit('change', this.id);
            }
        },
        computed: {
            // 引入state数据源
            ...mapState('channels', ['data']),
            // 显示需要的频道
            showChannels() {
                if (this.isCollapsed) {
                    // 折叠状态
                    return this.data.slice(0, 8); // 折叠状态取8条数据
                } else {
                    // 展开状态
                    return this.data;
                }
            }
        },
        watch: {
            // 监控data是否有值
            data: {
                immediate: true,
                handler() {
                    if (this.data.length > 0) {
                        // data有值，则默认选中第一项
                        this.selectItem(this.data[0].id);
                    }
                }
            }

        }
    }
</script>

<style lang="scss" scoped>
    .channel {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;

        .item {
            margin: 6px 12px;

            .el-button {
                background-color: transparent;
                color: #606266;
            }
        }

        a {
            line-height: 52px;
            text-decoration: none;
            /*background-color: #2e87cd;*/
        }
    }

    .active {
        background-color: #b3fae9;
        border-radius: 5px;

    }

</style>
